<template>
  <div class="component-pc__group-chat">
    <div
      class="chat-window"
      @click="is_show_emoji_picker = false"
      id="message_box"
    >
      <div class="message-item" v-for="(item, index) in message" :key="index">
        <template v-if="item.userId && item.userId != user_info.id">
          <div class="item-avatar">
            <img :src="item.avatar" />
          </div>
          <div class="item-message">
            <div class="message-top">
              <div>
                <span
                  :class="[item.userId == teacher_obj.id ? 'author' : null]"
                  >{{ item.acName }}</span
                >
                <span class="message-time">{{ trimDate(item.date) }}</span>
              </div>
              <div class="other" v-if="item.userId == teacher_obj.id">
                课程老师
              </div>
            </div>
            <div class="message-body">{{ item.message }}</div>
          </div>
          <div class="other-box"></div>
        </template>
        <template v-if="item.userId == user_info.id">
          <div class="other-box"></div>
          <div class="item-message" style="min-width: 70%;">
            <div
              class="message-top"
              style="text-align: right;display: flex;justify-content: flex-end;margin-right:7px;"
            >
              <div>
                <span class="message-time" style="margin-right:7px">{{
                  trimDate(item.date)
                }}</span>
                <span
                  :class="[item.userId == teacher_obj.id ? 'author' : null]"
                  >{{ item.acName }}</span
                >
              </div>
              <div class="other" v-if="item.userId == teacher_obj.id">
                课程老师
              </div>
            </div>
            <div class="message-body" style="text-align:right;">
              {{ item.message }}
            </div>
          </div>
          <div class="item-avatar">
            <img :src="item.avatar" />
          </div>
        </template>
        <template v-if="!item.userId">
          <div
            class="item-message"
            style="font-size: 16px;color: var(--theme-color);margin: 10px 0px;ter;"
          >
            {{ item.message }}
          </div>
        </template>
      </div>
    </div>
    <div class="fixed-box"></div>
    <div class="chat-input-container">
      <div class="chat-emoji" v-show="is_show_emoji_picker">
        <VEmojiPicker @select="selectEmoji" />
        <div :class="['emoji-action']" v-show="is_show_emoji_picker">
          <button @click="toggleEmojiPicker">
            <van-icon name="arrow-down" />
          </button>
          <button
            :class="[!text ? 'dark' : null]"
            @click="handlePostText"
            style="font-size: 20px;vertical-align: bottom;"
          >
            <!-- <van-icon name="passed" /> -->
            发送
          </button>
        </div>
      </div>
      <div class="chat-input">
        <div class="input-box">
          <van-form @submit="onSubmit" ref="form_text">
            <van-field
              v-model="text"
              label=""
              name="text"
              placeholder="输入内容"
              id="text_input"
              autocomplete="off"
            />
          </van-form>
        </div>
        <div class="emoji-input" @click="toggleEmojiPicker">
          <van-icon name="smile-o" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import VEmojiPicker from "v-emoji-picker";
import { socketUrl } from "~/config/conf";
import { sendMessage } from "~/api/course";
import { mapState, mapActions, mapMutations } from "vuex";
export default {
  components: {
    VEmojiPicker
  },
  props: ["chapter_obj", "teacher_obj", "live_status"],
  data() {
    return {
      text: "",
      is_show_emoji_picker: false,
      start_str: "", //
      end_str: "",
      websock: null, //聊天socket
      message: [], //消息列表
      error_count: 0 //socket重连次数
    };
  },
  computed: {
    ...mapState({
      user_info(state) {
        return state.user_info;
      },
      is_mobile(state) {
        return state.is_mobile;
      },
      token(state) {
        return state.token;
      }
    }),
    window_height() {
      let dom = document.querySelector("#message_box");
      if (dom) {
        return dom.scrollHeight;
      } else {
        return 0;
      }
    }
  },
  watch: {
    message: {
      handler(a, b, c) {
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      },
      deep: true // 必须加这个属性
    },
    chapter_obj: {
      handler(a, b, c) {
        this.$nextTick(async () => {
          await this.closeConnection();
          this.initState();
          if (this.chapter_obj && [1, 2].includes(this.chapter_obj.isLive)) {
            this.initWebSocket();
          }
          this.scrollToBottom();
        });
      },
      deep: true
    },
    async live_status(new_val) {
      if (new_val != 1) {
        await this.closeConnection();
      } else {
        if (!this.websock) {
          this.initWebSocket();
        }
      }
    }
  },
  destroyed() {
    this.closeConnection();
  },
  deactivated() {
    this.closeConnection();
  },
  activated() {
    this.initState();
    if (this.chapter_obj && [1, 2].includes(this.chapter_obj.isLive)) {
      this.initWebSocket();
    }
    this.$nextTick(() => {
      this.scrollToBottom();
    });
  },
  methods: {
    selectEmoji(emoji) {
      let current_text_index =
        document.querySelector("#text_input").selectionStart ||
        this.text.length;
      //输入框光标的位置
      console.log("current_text_index:", current_text_index);
      let start_str = this.text.substring(0, current_text_index);
      let end_str = this.text.substring(current_text_index, this.text.length);
      console.log(emoji);
      this.text = start_str + emoji.data + end_str;
    },
    toggleEmojiPicker(event) {
      event.preventDefault();
      event.stopPropagation();
      this.is_show_emoji_picker = !this.is_show_emoji_picker;
    },
    stopEvent(event) {
      event.preventDefault();
      event.stopPropagation();
    },
    handlePostText() {
      if (!this.text) {
        return;
      }
      this.$refs["form_text"].submit();
    },
    async onSubmit(value) {
      console.log("value:", value);
      if (!value.text) {
        return;
      }
      let params = {
        action: "send_group_msg",
        groupId: this.chapter_obj.id,
        message: value.text,
        userId: this.user_info.id,
        avatar: this.user_info.avatar,
        acName: this.user_info.acName,
        echo: new Date().getTime()
      };
      console.log("params:", params);
      let result = await sendMessage(params);
      if (result && result.data && result.data.code == 200) {
        this.text = "";
      } else {
        this.$Message.error("发送失败！请检查网络是否通畅");
      }
      //   this.websocketsend(params);
      //   this.message = [
      //     ...this.message,
      //     {
      //       name: 111,
      //       message: value.text,
      //       avatar:
      //         "https://keelea.oss-cn-zhangjiakou.aliyuncs.com/keelea/picture/avatar/1594097756373-657af91c-2441-4c69.jpeg",
      //       time: "21:00"
      //     }
      //   ];
    },
    scrollToBottom() {
      console.log("滑动！！");
      if (process.client) {
        console.log(document.querySelector("#message_box").scrollHeight);
        document.querySelector(
          "#message_box"
        ).scrollTop = document.querySelector("#message_box").scrollHeight;
      }
    },
    initWebSocket() {
      if (process.client) {
        if ("WebSocket" in window) {
          if (this.live_status != 1) {
            return;
          }
          //初始化weosocket
          console.log("初始化weosocket:");
          let groupId = this.chapter_obj ? this.chapter_obj.id : null;
          let wsuri = socketUrl + groupId + "/" + this.user_info.id;
          this.websock = new WebSocket(wsuri);
          this.websock.onmessage = this.websocketonmessage;
          this.websock.onopen = this.websocketonopen;
          this.websock.onerror = this.websocketonerror;
          this.websock.onclose = this.websocketclose;

          window.addEventListener("beforeunload", this.closeConnection, false);
        } else {
          this.$Message.error("当前环境不支持websocket");
        }
      }
    },
    websocketonopen() {
      //连接建立之后执行send方法发送数据
      console.log("成功建立socket连接");
      this.websocketsend(
        JSON.stringify({
          type: "chatEntry",
          data: {
            action: "send_group_msg",
            groupId: this.chapter_obj.id,
            userId: this.user_info.id,
            avatar: this.user_info.avatar,
            acName: this.user_info.acName,
            echo: new Date().getTime()
          }
        })
      );
    },
    websocketonerror() {
      //连接建立失败重连
      this.error_count = this.error_count + 1;
      if (this.error_count <= 10) {
        setTimeout(() => {
          this.initWebSocket();
        }, 2000);
      }
    },
    websocketonmessage(e) {
      //数据接收
      console.log("收到socket:", e);
      console.log(e.data || e);
      this.error_count = 0;
      try {
        let result = JSON.parse(e.data);
        this.message = [
          ...this.message,
          {
            ...result,
            avatar: result.avatar ? result.avatar : "/img/pc/avatar04.png"
          }
        ];
      } catch (e) {
        console.log(e);
      }
    },
    websocketsend(Data) {
      //数据发送
      this.websock.send(Data);
    },
    async websocketclose(e) {
      //关闭
      console.log("断开连接", e);
      await this.closeConnection();
      if (this.error_count <= 10) {
        setTimeout(() => {
          this.initWebSocket();
        }, 2000);
      }
    },
    closeConnection() {
      return new Promise((res, rej) => {
        try {
          window.removeEventListener("beforeunload", this.closeConnection);
          this.websock && this.websock.close();
        } catch (e) {
          console.log("关闭socket错误：", e);
        }
        res();
      }).then();
    },
    trimDate(date) {
      if (date) {
        let _date = new Date(date);
        return `${_date.getFullYear()}/${_date.getMonth() +
          1}/${_date.getDate()}  ${_date.getHours()}:${_date.getMinutes()}:${_date.getSeconds()}`;
      } else {
        return "未知";
      }
    },
    initState() {
      this.text = "";
      this.is_show_emoji_picker = false;
      this.start_str = ""; //
      this.end_str = "";
      this.websock = null; //聊天socket
      this.message = []; //消息列表
    }
  },
  created() {
    if (this.chapter_obj && [1, 2].includes(this.chapter_obj.isLive)) {
      this.initWebSocket();
    }
    this.$nextTick(() => {
      this.scrollToBottom();
    });
  },
  mounted() {}
};
</script>

<style lang="scss">
.component-pc__group-chat {
  position: relative;
  overflow: auto;
  height: 100%;
  .chat-window {
    height: 100%;
    background-color: #fff;
    padding: 0px 12px 47px;
    overflow: auto;
    &::-webkit-scrollbar {
      border-radius: 4px;
      width: 4px;
      background: #7c7c7c5b;
    }
    &::-webkit-scrollbar-thumb {
      border-radius: 4px;
      background: #00000038;
    }
    &::-webkit-scrollbar-track {
      border-radius: 4px;
    }
    .message-item {
      display: flex;
      .item-avatar {
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 7px;
        width: 34px;
        height: 34px;
        border-radius: 4px;
        overflow: hidden;
        > img {
          width: 100%;
          height: 100%;
        }
      }
      .item-message {
        .message-top {
          display: flex;
          flex-wrap: wrap;
          align-items: center;
          height: 34px;
          font-size: 14px;
          color: #333;
          .message-time {
            margin-left: 7px;
            font-size: 12px;
            color: #999;
          }
          .other {
            width: 100%;
            font-size: 12px;
            color: #999;
          }
          .author {
            color: var(--theme-color);
          }
        }
        .message-body {
          margin-top: 12px;
          font-size: 14px;
          color: #666;
        }
      }
      .other-box {
        flex: 1;
      }
    }
    .message-item + .message-item {
      margin-top: 12px;
    }
  }
  .fixed-box {
    width: 100%;
    height: 0;
  }
  .chat-input-container {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    z-index: 9;
    .chat-input {
      width: 100%;
      height: 40px;
      border-top: 1px solid #fcfcfc;
      display: flex;
      .input-box {
        flex: 1;
        padding: 4px 0px 4px 12px;
        background-color: #f6f6f6;
      }
      .van-cell {
        padding: 4px;
        border-radius: 4px;
      }
      .van-field__control {
        font-size: 14px;
      }
      .emoji-input {
        background-color: #f6f6f6;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0 12px;
        font-size: 25px;
        color: var(--theme-color);
      }
    }
    .chat-emoji {
      //   max-height: calc(100% - 1rem);
      overflow-y: auto;
      #EmojiPicker {
        width: 100%;
        .container-search {
          display: none;
        }
        .container-emoji {
          //   height: 5rem;
        }
      }
      .emoji-action {
        display: flex;
        align-items: center;
        position: absolute;
        bottom: 60px;
        right: 0;
        background-color: transparent;
        width: 30%;
        button {
          padding: 4px;
          background-color: rgba($color: #fff, $alpha: 0.8);
          border: none;
          border-radius: 4px;
          overflow: hidden;
          color: var(--theme-color);
          > i {
            font-size: 24px;
            color: var(--theme-color);
          }
        }
        button + button {
          margin-left: 12px;
        }
      }
      .dark {
        color: #999 !important;
      }
    }
  }
}
</style>
